package com.ruoyi.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.order.domain.Coupon;
import com.ruoyi.order.domain.UserCoupon;
import com.ruoyi.order.mapper.UserCouponMapper;
import com.ruoyi.order.service.ICouponService;
import com.ruoyi.order.service.IUserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 优惠券中间Service业务层处理
 *
 * @author jsj
 * @date 2024-03-27
 */
@Service
public class UserCouponServiceImpl  extends ServiceImpl<UserCouponMapper,UserCoupon> implements IUserCouponService {
    @Autowired
     UserCouponMapper userCouponMapper;



    @Autowired
    ICouponService couponService;


    /**
     * 根据用户id查询用户所有优惠劵的方法
     */
    public List<UserCoupon> selectUserCouponList(Long uid)
    {
        return userCouponMapper.selectCouponById(uid);

    }

    /**
     * 获取优惠劵信息，秒杀活动
     *  1、查询优惠劵信息
     *  2、把优惠信息存入redis中
     *  3、
     */

//    @Autowired
//    private RedisIdWorker redisIdWorker;

    public AjaxResult seckillVoucher(Long voucherId, Long uid) {


        //根据优惠卷id查询对应优惠卷信息
        Coupon coupon = couponService.selectCouponById(voucherId);

        //判断优惠劵开始抢购是否开始
        if (coupon.getStart().isAfter(LocalDateTime.now())) {
            return AjaxResult.error("抢购尚未开始");
        }
        //判断优惠劵开始抢购是否结束
        if (coupon.getEnd().isBefore(LocalDateTime.now())) {
            return AjaxResult.error("抢购已经结束");
        }
        //判断库存是否充足
        if (coupon.getSize() < 1) {
            return AjaxResult.error("优惠劵已经抢完了");
        }

        //一人一单
//        Long userId = UserHolder.getUser().getId();
        //查询订单
        QueryWrapper<UserCoupon> wrapper = new QueryWrapper<>();
         wrapper.eq("u_id", uid).eq("c_id", voucherId);
        List<UserCoupon> userCoupons = userCouponMapper.selectList(wrapper);

        //判断是否存在
        if (userCoupons.size() > 0){
            return AjaxResult.error("您已购买过一次！");
        }

        //扣减库存，用mybatis-plus来写
        boolean success =
                couponService.update().
                        setSql("size = size - 1").
                        eq("id", voucherId).
                        gt("size",0).update();//where条件
        if (!success){
            return AjaxResult.error("库存不足");
        }
        System.out.println("111111111111111111111111");
        //创建中间表数据，写入中间表
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setuId(uid);
        userCoupon.setcId(voucherId);
        int i = userCouponMapper.insert(userCoupon);
        if (i == 0){
            return AjaxResult.error("抢购优惠劵失败");
        }

        return AjaxResult.success("抢购优惠劵成功");
    }


}
